<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stream Data Example</title>
</head>
<body>
    <h1>Stream Data Example</h1>
    <div>
        <label for="message-input">Enter Message:</label>
        <input type="text" id="message-input" placeholder="Type a message">
        <button id="send-button">Send</button>
    </div>
    <div id="data-container"></div>

    <script>
        // 获取页面元素
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const dataContainer = document.getElementById('data-container');

        // 点击按钮触发事件
        sendButton.addEventListener('click', function() {
            const message = messageInput.value.trim(); // 获取输入框的值
            if (!message) {
                alert('Please enter a message!');
                return;
            }

            // 调用后端接口
            const url = `http://localhost:8080/ai/generateStreamStr?message=${encodeURIComponent(message)}`;
            fetchData(url);
        });

        // 使用 EventSource 接收流数据
        function fetchData(url) {
            // 关闭之前的 EventSource 连接（如果存在）
            if (window.eventSource) {
                window.eventSource.close();
            }
			
			dataContainer.textContent = ""
            // 创建新的 EventSource 连接
            window.eventSource = new EventSource(url);

            // 监听消息事件
            window.eventSource.onmessage = function(event) {
                const data = event.data; // 获取数据
                console.log('Received data:', data);

                // 将数据展示到页面上
                //const newDataElement = document.createElement('p');
                //newDataElement.textContent = data;
                //dataContainer.appendChild(newDataElement);
                dataContainer.textContent += data;
            };

            // 监听错误事件
            window.eventSource.onerror = function(error) {
                console.error('EventSource failed:', error);
                window.eventSource.close(); // 关闭连接
            };
        }
    </script>
</body>
</html>